// Copyright 2017 Baidu Inc. All Rights Reserved.
// Author: Su Hao (suhao@baidu.com)
//
// Description: Configuration

#include "baidu_ca_configuration.h"
#include <mbed.h>
#ifdef TARGET_UNO_91H
#include "rda5991h_wland.h"
#endif
#include "baidu_ca_adapter.h"
#include "heap_monitor.h"
#include "duer_log.h"

#define PROFILE_PATH    "/sd/profile"

namespace duer {

Configuration::Configuration() : _data(NULL), _size(0) {
    FILE* file = NULL;
    char* data = NULL;

#if 0
	
#if defined(TARGET_UNO_91H)
    int rs;
    rs = rda5981_flash_read_3rdparter_data_length();

    if (rs < 0) {
        DUER_LOGW("Failed to load Profile from flash: rs = %d", rs);
        goto sdcard;
    }

    _size = rs;
    data = NEW(CA) char[_size + 1];
    rs = rda5981_flash_read_3rdparter_data((unsigned char*)data, _size);

    if (rs < 0) {
        DUER_LOGW("Failed to load Profile from flash: rs = %d", rs);
        delete [] data;
        goto sdcard;
    }

    data[_size] = '\0';
    _data = data;
    DUER_LOGV("XXX: %d --> %s", _size, _data);
    goto exit;
sdcard:
#endif

#endif

    file = fopen(PROFILE_PATH, "rb");

    if (!file) {
        DUER_LOGE("Failed to open <%s>", PROFILE_PATH);
        goto exit;
    }

    fseek(file, 0, SEEK_END);
    _size = (size_t)ftell(file);
    data = NEW(CA) char[_size];

    if (!data) {
        goto exit;
    }

    fseek(file, 0, SEEK_SET);
    fread(data, 1, _size, file);
    _data = data;
exit:

    if (file) {
        fclose(file);
    }

    if (_data == NULL) {
        _size = 0;
    }
}

Configuration::~Configuration() {
    if (_data) {
        delete [](char*)_data;
        _data = NULL;
    }
}

const void* Configuration::get_data() const {
    return _data;
}

bca_size_t Configuration::get_size() const {
    return _size;
}

} // namespace duer

